package cn.chenfei.sshd.client.common;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static cn.chenfei.sshd.client.common.Constant.CONNECT_JSON_FILE;

public class SettingUtils {

    /**
     * 添加连接数据
     *
     * @param sshConnect
     */
    public static void saveConnect(SshConnect sshConnect) {
        File touch = FileUtil.touch(CONNECT_JSON_FILE);
        List<SshConnect> sshConnectList = listConnect();
        sshConnectList.add(sshConnect);
        String jsonStr = JSONUtil.toJsonStr(sshConnectList);
        FileUtil.writeString(JSONUtil.formatJsonStr(jsonStr), touch, StandardCharsets.UTF_8);
    }

    /**
     * 编辑连接数据
     *
     * @param index
     * @param sshConnect
     */
    public static void updateConnect(int index, SshConnect sshConnect) {
        File touch = FileUtil.touch(CONNECT_JSON_FILE);
        List<SshConnect> sshConnectList = listConnect();
        sshConnectList.set(index, sshConnect);
        String jsonStr = JSONUtil.toJsonStr(sshConnectList);
        FileUtil.writeString(JSONUtil.formatJsonStr(jsonStr), touch, StandardCharsets.UTF_8);
    }

    /**
     * 查询连接数据
     *
     * @return
     */
    public static List<SshConnect> listConnect() {
        if (!FileUtil.exist(CONNECT_JSON_FILE)) {
            FileUtil.touch(CONNECT_JSON_FILE);
            return new ArrayList<>();
        }
        String readString = FileUtil.readString(CONNECT_JSON_FILE, StandardCharsets.UTF_8);
        if (StrUtil.isBlank(readString)) {
            return new ArrayList<>();
        }
        return JSONUtil.toList(readString, SshConnect.class);
    }

}
